<template>
	<view class="container" v-if="orderDetail.id">
		<view class="state">
			<text>{{ ORDER_STATUS_TEXT[orderDetail.status] }}</text>
		</view>
		<view class="info">
			<view class="item">
				<text class="label">订单编号</text>
				<text class="value">{{ orderDetail.order_no  }}</text>
			</view>
			<view class="item">
				<text class="label">支付方式</text>
				<text class="value">微信</text>
			</view>
			<view class="item">
				<text class="label">支付金额</text>
				<text class="value">¥{{ orderDetail.payment_amount }}</text>
			</view>
			<view class="item" v-if="orderDetail.status === ORDER_STATUS.PENDING && countdownText">
				<text class="label">剩余支付时间</text>
				<text class="value countdown">{{ countdownText }}</text>
			</view>
		</view>


    <view v-if="orderDetail.status === ORDER_STATUS.PENDING">
      <ZButton class="primary-button" style="margin-top: 60rpx" @click="getPay(orderDetail.id)">支付</ZButton>
    </view>
	</view>
</template>

<script>
	import { ORDER_STATUS, ORDER_STATUS_TEXT, ORDER_STATUS_ICON } from "../../utils/enum";
  import ZButton from "../../components/ZButton.vue";

  export default {
    components: {ZButton},
		data() {
			return {
        orderDetail: {},
        ORDER_STATUS,
        ORDER_STATUS_TEXT,
        ORDER_STATUS_ICON,
        countdownText: '',
        countdownTimer: null
			}
		},
		methods: {
      getOrderDetail(orderId) {
        this.$api.getOrderDetail(orderId).then(res => {
          // 展示订单状态
          this.orderDetail = res
          // 如果是待支付状态且有过期时间，启动倒计时
          if (res.status === ORDER_STATUS.PENDING && res.time_expire) {
            this.startCountdown(res.time_expire)
          }
        })
      },
      getPay(order_id){
        uni.showLoading({
          title:'微信支付请求'
        });
        const that = this
        this.$api.createPay({
          order_id
        }).then(payment=>{
          uni.requestPayment({
            provider: 'wxpay',
            timeStamp: payment.timestamp,
            nonceStr: payment.nonce_str,
            package: payment.package,
            signType: payment.signType,
            paySign: payment.paySign,
            success:(result)=> {
              uni.showToast({
                title:'支付成功'
              });
            },
            fail: (result) => {
              uni.showToast({
                icon:'none',
                title:'支付失败',
              });
            },
            complete: () => {
              uni.showLoading({
                title:'加载中...'
              })
              setTimeout(() => {
                that.getOrderDetail(order_id)
              }, 1000);
            }
          });
        }).catch(res=>{
          this.loading = false;
          setTimeout(() => {
            uni.navigateTo({
              url: "/pages/cart/paymentinfo?orderId=" + order_id
            })
          }, 1000);
        })
      },
      
      // 启动倒计时
      startCountdown(timeExpire) {
        // 清除之前的定时器
        if (this.countdownTimer) {
          clearInterval(this.countdownTimer)
        }
        
        const updateCountdown = () => {
          const now = new Date().getTime()
          const expireTime = new Date(timeExpire).getTime()
          const remainingTime = expireTime - now
          
          if (remainingTime <= 0) {
            this.countdownText = '订单已过期'
            clearInterval(this.countdownTimer)
            // 订单过期后刷新订单状态
            setTimeout(() => {
              this.getOrderDetail(this.orderDetail.id)
            }, 1000)
            return
          }
          
          // 计算剩余时间
          const hours = Math.floor(remainingTime / (1000 * 60 * 60))
          const minutes = Math.floor((remainingTime % (1000 * 60 * 60)) / (1000 * 60))
          const seconds = Math.floor((remainingTime % (1000 * 60)) / 1000)
          
          this.countdownText = `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`
        }
        
        // 立即执行一次
        updateCountdown()
        
        // 每秒更新一次
        this.countdownTimer = setInterval(updateCountdown, 1000)
      },
      
      // 清除倒计时
      clearCountdown() {
        if (this.countdownTimer) {
          clearInterval(this.countdownTimer)
          this.countdownTimer = null
        }
        this.countdownText = ''
      },
		},
    onLoad({ orderId }) {
      if (!this.$store.state.userInfo.id || !orderId) {
        // 退出到首页
        uni.reLaunch({
          url: '/pages/index/index'
        })
      }
      uni.showLoading({
        title: '加载中...'
      })
      setTimeout(() => {
        this.getOrderDetail(orderId)
      }, 1000)
    },
    
    onUnload() {
      // 页面卸载时清除倒计时
      this.clearCountdown()
    }
	}
</script>

<style>
	page {
		background: #F5F5F5;
	}
</style>

<style lang="scss">
	.container {
		margin: 30rpx;
	}
  .btn {
    margin-top: 70rpx;
    width: 100%;
    padding: 0 30rpx;
    button {
      flex: 1;
      border-radius: 46rpx;
      background: #FFD29F;
      color: #FFFFFF;
      font-size: 30rpx;
      padding: 12rpx 0rpx;
    }
  }

	.state {
		display: flex;
		flex-direction: column;
		align-items: center;
		margin: 20rpx 0rpx 60rpx 0rpx;

		image {
			width: 120rpx;
			height: 120rpx;
		}

		text {
			font-size: 30rpx;
			font-weight: 600;
			margin-top: 28rpx;
		}
	}

	.info {
		background: #FFFFFF;
		border-radius: 20rpx;
		padding: 0rpx 30rpx;

		.item {
			display: flex;
			align-items: center;
			justify-content: space-between;
			padding: 28rpx 0rpx;

			.label {
				font-size: 30rpx;
				color: #999999;
			}

			.value {
				font-size: 30rpx;
				color: #333333;
			}
		}

		.item:not(:last-child) {
			border-bottom: 1rpx solid #ECECEC;
		}
		
		.countdown {
			color: #FF6B6B !important;
			font-weight: 600;
		}
	}
</style>
